/*================================================================
*   Copyright (C) 2023 baichao All rights reserved.
*   
*   文件名称：main_windows.cpp
*   创 建 者：baichao
*   创建日期：2023年12月12日
*   描    述：
*
================================================================*/

#include <stdio.h>
#include <windows.h>

int mkdir_p(const char* dir_path) {
    char tmp[MAX_PATH];
    char* p = NULL;

    // Copy the input string to a temporary buffer
    strncpy(tmp, dir_path, MAX_PATH);

    // Iterate over each component of the directory path
    for (p = tmp + (*tmp == '\\'); *p; p++) {
        if (*p == '\\') {
            *p = '\0';

            // Attempt to create the current directory
            if (CreateDirectory(tmp, NULL) == 0 && GetLastError() != ERROR_ALREADY_EXISTS) {
                fprintf(stderr, "mkdir_p: %s: %d\n", tmp, GetLastError());
                return -1;
            }

            *p = '\\';
        }
    }

    // Attempt to create the final directory
    if (CreateDirectory(tmp, NULL) == 0 && GetLastError() != ERROR_ALREADY_EXISTS) {
        fprintf(stderr, "mkdir_p: %s: %d\n", tmp, GetLastError());
        return -1;
    }

    return 0;
}

int create_directory(const char* dir_path) {
    DWORD attr;

    // Check if the directory already exists
    attr = GetFileAttributes(dir_path);
    if (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY)) {
        printf("Directory already exists: %s\n", dir_path);
        return 1;
    }

    // Attempt to create the directory
    if (mkdir_p(dir_path) == 0) {
        printf("Directory created successfully: %s\n", dir_path);
        return 1;
    } else {
        perror("Failed to create directory");
        return 0;
    }
}

int main()
{
    create_directory("/home/baichao/code/c++/cpp_test/folder/data/data1");
}
